<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
          <!-- <el-col :span="12">
            <el-form-item label="巡检计划" prop="maintenancePlanId">
              <el-select v-model="formData.maintenancePlanId" placeholder="请选择巡检计划" style="width: 100%;" filterable remote :remote-method="remoteMethod" :loading="planLoading" :disabled="currentForceMaintenancePlanId">
                <el-option v-for="plan in maintenancePlanList" :key="plan.id" :label="plan.planName" :value="plan.id"/>
              </el-select>
              <div v-if="currentForceMaintenancePlanId" class="el-form-item__tip">维护计划由系统自动设置，不可修改</div>
            </el-form-item>
          </el-col> -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="保养内容">
              <Editor v-model="formData.planContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaintenancePlanItemApi from '@/api/devices/maintenanceplanitem';
import * as MaintenancePlanApi from '@/api/devices/maintenanceplan/index.js'; // 导入巡检计划API
import Editor from '@/components/Editor';

export default {
  name: "MaintenancePlanItemForm",
  components: {
    Editor,
  },
  props: {
    // 从父组件传递的默认维护计划ID
    defaultMaintenancePlanId: {
      type: Number,
      default: undefined
    },
    // 是否强制使用维护计划ID（不可修改）
    forceMaintenancePlanId: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 巡检计划远程搜索加载状态
      planLoading: false,
      // 巡检计划列表
      maintenancePlanList: [],
      // 表单参数
      formData: {
        id: undefined,
        maintenancePlanId: undefined,
        planContent: undefined,
        sort: undefined,
      },
      // 表单校验
      formRules: {},
      // 当前是否强制使用维护计划ID
      currentForceMaintenancePlanId: false
    };
  },
  methods: {
    /** 远程搜索巡检计划 */
    async remoteMethod(query) {
      if (query !== '') {
        this.planLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            cycleType: 1,
            planName: query // 根据计划名称搜索
          };
          const response = await MaintenancePlanApi.getMaintenancePlanPage(params);
          this.maintenancePlanList = response.data.list;
        } catch (error) {
          console.error('搜索巡检计划失败', error);
          this.maintenancePlanList = [];
        } finally {
          this.planLoading = false;
        }
      } else {
        // 如果搜索框清空，加载全部巡检计划
        this.getMaintenancePlanList();
      }
    },
    
    /** 获取巡检计划列表 */
    async getMaintenancePlanList() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100, // 分页数量传100
          cycleType: 1 // 默认值设为1
        };
        const response = await MaintenancePlanApi.getMaintenancePlanPage(params);
        this.maintenancePlanList = response.data.list;
      } catch (error) {
        console.error('获取巡检计划列表失败', error);
        this.maintenancePlanList = [];
      }
    },
    
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      
      // 保存当前强制状态
      this.currentForceMaintenancePlanId = this.forceMaintenancePlanId;
      
      // 加载巡检计划列表
      await this.getMaintenancePlanList();
      
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaintenancePlanItemApi.getMaintenancePlanItem(id);
          this.formData = res.data;
          // 如果强制使用维护计划ID，确保设置正确的值
          if (this.currentForceMaintenancePlanId && this.defaultMaintenancePlanId) {
            this.formData.maintenancePlanId = this.defaultMaintenancePlanId;
          }
          this.dialogTitle = "编辑计划内容"; // 设置编辑标题
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增计划内容"; // 设置新增标题
        
        // 如果有默认维护计划ID，则设置
        if (this.defaultMaintenancePlanId) {
          this.formData.maintenancePlanId = this.defaultMaintenancePlanId;
          // 由于使用了远程搜索，我们需要确保列表中有这个ID对应的选项
          // 如果当前列表中没有，可能需要根据ID搜索具体的计划
          const hasPlan = this.maintenancePlanList.some(plan => plan.id === this.defaultMaintenancePlanId);
          if (!hasPlan && this.$refs.formRef) {
            // 如果列表中没有，尝试根据ID获取具体信息
            try {
              // 这里假设MaintenancePlanApi有一个getMaintenancePlan方法
              // 如果没有，可以考虑其他方式获取计划信息
              const planList = this.maintenancePlanList;
              // 强制触发表单验证更新
              this.$nextTick(() => {
                this.$refs.formRef.validateField('maintenancePlanId');
              });
            } catch (error) {
              console.error('获取维护计划详情失败', error);
            }
          }
        }
      }
      
      // 返回Promise以便父组件可以知道何时打开完成
      return Promise.resolve();
    },
    
    /**
     * 从父组件设置默认维护计划ID
     * @param {Number} maintenancePlanId 维护计划ID
     */
    setDefaultMaintenancePlanId(maintenancePlanId) {
      // 由于props是只读的，我们不能直接修改，但可以影响formData
      if (this.formData.id === undefined) { // 只在新增模式下设置
        this.formData.maintenancePlanId = maintenancePlanId;
        // 如果表单已打开，触发表单验证
        if (this.dialogVisible) {
          this.$nextTick(() => {
            if (this.$refs.formRef) {
              this.$refs.formRef.validateField('maintenancePlanId');
            }
          });
        }
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await MaintenancePlanItemApi.updateMaintenancePlanItem(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await MaintenancePlanItemApi.createMaintenancePlanItem(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        maintenancePlanId: undefined,
        planContent: undefined,
        sort: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
